<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchParam.ironDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getironDate"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
        <el-button type="primary" @click="materialImport">
          <template #icon><i-ep-upload /></template>白班导入
        </el-button>
        <el-button type="primary" @click="materialImport1">
          <template #icon><i-ep-upload /></template>夜班导入
        </el-button>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesironweight/export',
              '出铁实际重量填报',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="班次"
          prop="shiftName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="日期"
          prop="ironDate"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="时间"
          prop="ironDateTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品包次"
          prop="materialPack"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁时间"
          prop="ironTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁目标重量"
          prop="targetWeight"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁实际重量"
          prop="actualWeight"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁目标重量上限"
          prop="actualPackage"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁时间目标"
          prop="ironTarget"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="包数"
          prop="packNum"
          min-width="50"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁时间异常"
          prop="ironAbnormalTime"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column
          label="出铁重量下限-2"
          prop="targetWeightMin"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁重量上限+2"
          prop="targetWeightMax"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="炉号"
          prop="stoveNum"
          min-width="50"
          show-overflow-tooltip
        />
        <el-table-column
          label="出铁重量异常"
          prop="ironAbnormalWeight"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="加料后到出铁50KG时间"
          prop="ingredientsTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button> -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesironweight-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- 导入 -->
    <ImportExcel ref="materialImportRef" />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESIRONWEIGHT",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesironweight/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  ironDateSearch: [],
  ironDateStart: "",
  ironDateEnd: "",
  ironDateTimeSearch: [],
  ironDateTimeStart: "",
  ironDateTimeEnd: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  enabled: "",
  deleted: "",
};

const deleteParam = {
  api: "/mes/mesironweight/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesironweight/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开出铁实际重量填报表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改出铁实际重量填报";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增出铁实际重量填报";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开出铁实际重量填报表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "出铁实际重量填报详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getironDate(data: any) {
  if (data) {
    searchParam.value.ironDateStart = data[0];
    searchParam.value.ironDateEnd = data[1];
  } else {
    searchParam.value.ironDateStart = "";
    searchParam.value.ironDateEnd = "";
  }
}
function getironDateTime(data: any) {
  if (data) {
    searchParam.value.ironDateTimeStart = data[0];
    searchParam.value.ironDateTimeEnd = data[1];
  } else {
    searchParam.value.ironDateTimeStart = "";
    searchParam.value.ironDateTimeEnd = "";
  }
}
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

// 导入excel
const uploadApi = "/mes/mesironweight/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesironweight/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
const materialImportRef = ref();
async function materialImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mes/mesironweight/upload", formdata, config)
    .then((res: any) => {});
}
async function materialImportApiFunc1(formdata: FormData, config: any) {
  await request
    .post("/mes/mesironweight/upload1", formdata, config)
    .then((res: any) => {});
}
const materialImport = () => {
  let newSearchParam = { ...searchParam.value };
  let params = {
    title: "出铁实际重量填报",
    tempApi: "/mes/mesironweight/exportTemp", //模板下载
    importApi: materialImportApiFunc, // 导入
    getTableList, // 成功后回调
    isShowTemp: true, // 是否显示下载模板
    fileTypes: ".xlsx",
    searchParam: newSearchParam,
    isOK: true, // 是否显示成功条数
  };
  materialImportRef.value.acceptParams(params);
};

const materialImport1 = () => {
  let newSearchParam = { ...searchParam.value };
  let params = {
    title: "出铁实际重量填报",
    tempApi: "/mes/mesironweight/exportTemp", //模板下载
    importApi: materialImportApiFunc1, // 导入
    getTableList, // 成功后回调
    isShowTemp: true, // 是否显示下载模板
    fileTypes: ".xlsx",
    searchParam: newSearchParam,
    isOK: true, // 是否显示成功条数
  };
  materialImportRef.value.acceptParams(params);
};
</script>
